<template>
  <div class="app-container">
    <div class="titleAndGit-container">
      <div class="version-container">
        <div class="version-content">
          <span>当前版本：{{versionNo}}</span>
        </div>
        <div class="update-content">
          <el-button 
            type="success" 
            :loading="updateLoading" 
            size="small"
            plain
            @click="checkIsLatest"
          >检查更新</el-button>
        </div>
      </div>
      <div class="title-container">
        <span>{{title}}</span>
      </div>
      <div class="gitWebSite-container" @click="openToMyGitee">
        <span title="跳转链接">我的gitee</span>
      </div>
    </div>
    <div 
      class="hrefAndLog-container" 
      v-loading="logLoading"
      element-loading-text="加载日志中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.6)"
    >
      <div class="leftNavTitle-list" @mouseenter="navEnter" @mouseleave="navLeave">
        <div
          v-for="(item, index) in logs"
          :key="index"
          :style="[
            {'padding-left': 8 + 16*(item.titleLevel - 1) + 'px'}
          ]"
          class="leftNavTitle-item"
        >
          <div 
            class="navTitle" 
            @click="goTo(item.anchor)"
            :class="currentAnchor == item.anchor ? 'active-item' : ''"
          >
            <span>{{item.title}}</span>
          </div>
        </div>
      </div>
      <div class="log-container" :class="getLogContainerClass()" @scroll="watchCurrentAnchorByScroll">
        <div
           v-for="(item, i) in logs"
          :key="i"
          class="logs-page"
        >
          <h1 v-if="item.titleLevel == 1" :id="item.anchor">{{item.title}}</h1>
          <h2 v-if="item.titleLevel == 2" :id="item.anchor">{{item.title}}</h2>
          <h3 v-if="item.titleLevel == 3" :id="item.anchor">{{item.title}}</h3>
          <h4 style="line-height: 35px" v-if="item.titleLevel == 4" :id="item.anchor">{{item.title}}</h4>
          <div 
            class="logContent-list"
            v-if="item.logContents.length"
          >
            <div
              v-for="(content, index) in item.logContents"
              :key="index"
              class="logContent-item"
            >
              <span>{{content}}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-backtop 
      title="返回顶部" 
      target=".log-container" 
      :visibility-height="100"
      :right="30"
      :bottom="30"
    ></el-backtop>
    <el-dialog
      v-if="dialogVisible"
      title="有新版本更新"
      :visible.sync="dialogVisible"
      width="30%"
      :modal-append-to-body="false"
    >
      <div>
        <div class="newTitle">
          <el-divider content-position="left"><span>最新版本:{{gitVersion}}</span></el-divider>
        </div>
        <div class="newInfo">
          <span>{{gitInfo}}</span>
        </div>
        <div class="update-method">
          <div class="intro">
            <el-divider content-position="left"><span>可以通过以下方式下载:</span></el-divider>
          </div>
          <div class="methodOne">
            <span>1.点击<span @click="openToMyGitee" class="methodOne-a">我的gitee</span>去下载dist文件</span>
          </div>
          <div class="methodTwo">
            <div>
              <span>2.QQ群文件：197396667</span>
            </div>
            <div @click="copySign" style="margin-left: 8px;cursor: pointer;">
              <el-tooltip effect="dark" content="复制QQ号" placement="top">
                <i class="el-icon-copy-document" style=""></i>
              </el-tooltip>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
const Base64 = require("js-base64").Base64
export default {
  name:'VersionLog',
  data() {
    return {
      logs: [],//日志文件
      updateLoading: false,//检查跟新按钮加载动画
      currentAnchor: "",
      dialogVisible: false,
      gitVersion: "",//获取的
      gitInfo: "",
      logLoading: false,
      htmlWidth: document.documentElement.clientWidth,
      isMouseInNav: false,
    }
  },
  computed: {
    ...mapGetters(['versionNo','title']),
  },
  mounted() {
    this.readLogs()
    this.$nextTick(()=>{
      this.reCollectEachHeight()
    })
    window.onresize = () => {
      this.htmlWidth = document.documentElement.clientWidth
      this.reCollectEachHeight()
    }
  },
  methods: {
    readLogs() {
      this.logLoading = true;
      let logJson = ""
      try {
        logJson = require("./log.json")
      } catch {
        this.logLoading = false
        this.$message.warning("加载资源失败，请刷新页面重试")
        return
      }
      if(logJson) {
        let logs = logJson.logs
        let index = logs.findIndex(x=>x.titleLevel == 3)
        let surplus = logs.splice(index, logs.length - index)
        let title3Arr = []
        for(let i = 0; i < surplus.length; i++) {
          if(surplus[i].titleLevel == 3) {
            title3Arr.push(i)
          }
        }
        let combArr = []
        for(let i = 0; i < title3Arr.length; i++) {
          let oneYearArr = []
          oneYearArr.push(surplus[title3Arr[i]])
          if(i == title3Arr.length - 1) {
            for(let j = surplus.length - 1; j > title3Arr[i]; j--) {
              oneYearArr.push(surplus[j])
            }
          } else {
            for(let j = title3Arr[i + 1] - 1; j > title3Arr[i]; j--) {
              oneYearArr.push(surplus[j])
            }
          }
          combArr.unshift(oneYearArr)
        }
        combArr = combArr.flat(Infinity)
        combArr.forEach(item=>{
          logs.push(item)
        })
        if(logs) {
          for(let i = 0; i < logs.length; i ++) {
            logs[i].anchor = "anchor-" + (i + 1)
          }
        }
        this.logs = logs
        this.logLoading = false
      }
    },
    openToMyGitee() {
      let isOnline = window.navigator.onLine;
      if(isOnline) {
        window.open("https://gitee.com/zjclxx/vue-bzhtglxt")
      } else{
        this.$confirm('你当前没有网络, 是否确定跳转页面?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          window.open("https://gitee.com/zjclxx/vue-bzhtglxt")
        }).catch(() => {
        });
      }
    },
    goTo(val) {
      this.currentAnchor = val
      // window.location.hash = "#" + val;//路由hash模式能跳转，但是刷新页面会找不到路由而一片空白
      document.getElementsByClassName("log-container")[0].scrollTop =
        document.getElementById(val).offsetTop -125;
    },
    checkIsLatest() {//检查更新
      this.updateLoading = true
      let isOnline = window.navigator.onLine;
      if(isOnline) {
        if(this.gitVersion) {//已经查过了
          if(this.gitVersion != this.versionNo) {
            this.dialogVisible = true
          } else {
            this.$message.success("当前已是最新版本")
          }
          this.updateLoading = false
        } else {//之前没查过
          this.$axios.get("https://gitee.com/api/v5/repos/zjclxx/vue-bzhtglxt/contents/version.json")
          .then(res=>{
            let gitFileInfoStr = Base64.decode(res.data.content)
            let gitFileInfo = JSON.parse(gitFileInfoStr)
            this.gitVersion = gitFileInfo.versionNo
            this.gitInfo = gitFileInfo.info
            if(this.gitVersion != this.versionNo) {
              this.dialogVisible = true
            } else {
              this.$message.success("当前已是最新版本")
            }
            this.updateLoading = false
          }).catch(err=>{
            this.$message.error("接口访问失败，可以刷新页面重试也可以先访问我的gitee")
            this.updateLoading = false
          })
        }
      } else{
        this.$message.warning("请先连接网络")
        this.updateLoading = false
      }
    },
    reCollectEachHeight() {//将高度数值放入数组
      if(this.logs) {
        this.logs.forEach(item=>{
          let h = document.getElementById(item.anchor)?.offsetTop
          if(h) {
            item.customHeight = h - 126.
          }
        })
      }
    },
    watchCurrentAnchorByScroll() {//监听滚动，然后显示高亮
      if(this.isMouseInNav) return;
      let currentScrollTop = document.getElementsByClassName("log-container")[0].scrollTop
      if(this.logs && this.logs.length) {
        for(let i = 0; i < this.logs.length; i++) {
          if(i == this.logs.length - 1) {
            this.currentAnchor = this.logs[i].anchor
            break
          } else {
            if(currentScrollTop >= this.logs[i].customHeight && currentScrollTop < this.logs[i+1].customHeight) {
              this.currentAnchor = this.logs[i].anchor
              break
            }
          }
        }
      }
    },
    navEnter() {
      this.isMouseInNav = true
    },
    navLeave() {
      this.isMouseInNav = false
    },
    copySign() {//复制QQ号
      this.$copyText("197396667").then((e) => {
        this.$message({
          type: "success",
          message: "已复制到剪切板"
        })
      }, (e) => {
        this.$message({
          type: "error",
          message: "复制失败，请重试"
        })
      })
    },
    getLogContainerClass() {
      // this.htmlWidth = document.documentElement.clientWidth
      if(this.htmlWidth > 860 && this.htmlWidth <= 1000) {
        return "log-container-rightNewPadding"
      } else if(this.htmlWidth <= 860 ) {
        return "log-container-leftNewPadding log-container-rightNewPadding"
      } else {
        return ""
      }
    },
  }
} 
</script>

<style lang='less' scoped>
  .app-container {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    .titleAndGit-container {
      width: 100%;
      min-height: 50px;
      display: flex;
      justify-content: space-around;
      align-items: center;
      flex-shrink: 0;
      background-color: wheat;
      .version-container {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        .version-content {
          font-size: 18px;
          margin-right: 16px;
        }
      }
      .title-container {
        font-size: 32px;
        font-weight: bold;
        text-transform: uppercase;//转大写
        -webkit-text-stroke: 2px black;//字的描边
        color: transparent;
        letter-spacing: 2px;//字符之间空隙
      }
      .gitWebSite-container {
        font-size: 20px;
        font-style: italic;
        cursor: pointer;
      }
      .gitWebSite-container:hover {
        span {
          color: rgb(39, 140, 14);
        }
      }
    }
    .hrefAndLog-container {
      width: 100%;
      flex: 1;
      display: flex;
      flex-shrink: 0;
      overflow: hidden;
      .leftNavTitle-list {
        padding-top: 16px;
        padding-bottom: 16px;
        padding-left: 8px;
        width: 220px;
        height: 100%;
        overflow-x: hidden;
        overflow-y: auto;
        background-color: aliceblue;
        box-sizing: border-box;
        .leftNavTitle-item {
          width: 100%;
          height: 30px;
          box-sizing: border-box;
          display: flex;
          align-items: center;
          .navTitle {
            cursor: pointer;
          }
          .navTitle:hover {
            color: #ff7700;
          }
          .navTitle.active-item {
            color: #e36c04;
            transform: scale(1.1);
          }
        }
      }
      .log-container {
        flex: 1;
        height: 100%;
        overflow-x: hidden;
        overflow-y: auto;
        padding: 16px 60px 16px 24px;
        box-sizing: border-box;
        .logs-page {
          width: 100%;
          box-sizing: border-box;
          h1 {
            line-height: 70px;
          }
          h2 {
            line-height: 60px;
          }
          h3 {
            line-height: 50px;
          }
          .logContent-list {
            width: 100%;
            max-width: 1000px;
            background-color: #e8e9ed;
            padding: 16px;
            box-sizing: border-box;
            .logContent-item {
              line-height: 24px;
            }
          }
        }
      }
      .log-container-rightNewPadding {
        padding-right: 16px;
      }
      .log-container-leftNewPadding {
        padding-left: 16px;
      }
    }
  }
  .newTitle {
    margin-bottom: 8px;
    span {
      font-size: 18px;
      font-weight: bold;
    }
  }
  .newInfo {
    white-space: pre-wrap;
  }
  .update-method {
    margin-top: 8px;
    .intro {
      margin-bottom: 4px;
    }
    .methodOne {
      margin-bottom: 4px;
      .methodOne-a {
        color: chocolate;
        cursor: pointer;
      }
      .methodOne-a:hover {
        color: red;
      }
    }
    .methodTwo {
      display: flex;
      align-items: center;
    }
  }
</style>